package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 执行DML语句--INSERT
 */
public class JDBCDemo2 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
    //需求:向user表中插入一条记录
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/tedu?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true",
                "root",
                "root");
        System.out.println("链接数据库成功");

        Statement statement=connection.createStatement();
        /**
         * INSERT INTO user(username,password,nickname,age)
         * VALUES('张三','123456','阿三',22)
         */
        String sql="INSERT INTO user(username,password,nickname,age) " +
                "VALUES('张三','123456','阿三',22)";
        //executeUpdate(增删盖都会对表进行改变,所以都可以用Update)
        // 执行SQL语句并返回受影响的行数
        int num = statement.executeUpdate(sql);
        // 根据受影响的行数判断操作是否成功
        System.out.println(num > 0 ? "添加成功" : "添加失败");
        // 关闭数据库连接
        connection.close();
    }
}
